/**
 * Created by ChenYong on 2017-04-12.
 *
 * 首页广告列表。
 */

$(function () {
    /** 创建人的 jQuery 对象 */
    var $homeAdCreatePerson = $("#home_ad_create_person");
    /** 广告标题 jQuery 对象 */
    var $homeAdName = $("#home_ad_name");
    /** 广告级别 jQuery 对象 */
    var $isShow = $("#is_show");
    /** 开始日期的 jQuery 对象 */
    var $startDate = $("#start_date");
    /** 结束日期的 jQuery 对象 */
    var $endDate = $("#end_date");
    /** 搜索按钮的 jQuery 对象 */
    var $searchAdvertBtn = $("#search_advert_btn");
    /** 广告列表的表格，DataTables 的 API 对象 */
    var advertTable = null;

    // 选择开始日期
    $startDate.datepicker({
        format: "yyyy-mm-dd",
        language: "zh-CN",
        clearBtn: true,
        autoclose: true,
        todayHighlight: true
    }).on("changeDate", function (e) {
        var startDate = ($.isNull(e.date) ? null : e.date);

        $endDate.datepicker("setStartDate", startDate);
    });

    // 选择结束日期
    $endDate.datepicker({
        format: "yyyy-mm-dd",
        language: "zh-CN",
        clearBtn: true,
        autoclose: true,
        todayHighlight: true
    }).on("changeDate", function (e) {
        var endDate = ($.isNull(e.date) ? null : e.date);

        $startDate.datepicker("setEndDate", endDate);
    });

    // 监听广告级别下拉列表搜索
    $isShow.change(function () {
        searchData();
    });

    // 点击搜索按钮
    $searchAdvertBtn.click(function (e) {
        searchData();
    });

    // 点击显示图片
    $(document).on("click", ".is_show_open", function () {
        var $this = $(this);
        var id = $this.data("id");

        $.showConfirmModal({
            msg: "确定显示此广告吗？",
            confirmFn: function () {
                $.myAjax({
                    url: "web/home/advert/is_show.json",
                    type: "post",
                    modal: true,
                    data: {
                        ids: id,
                        isShow: "1"
                    },
                    successFn: function (data) {
                        searchData();
                    }
                });
            }
        });
    });

    // 点击隐藏图片
    $(document).on("click", ".is_show_close", function () {
        var $this = $(this);
        var id = $this.data("id");

        $.showConfirmModal({
            msg: "确定隐藏此广告吗？",
            confirmFn: function () {
                $.myAjax({
                    url: "web/home/advert/is_show.json",
                    type: "post",
                    modal: true,
                    data: {
                        ids: id,
                        isShow: "0"
                    },
                    successFn: function (data) {
                        searchData();
                    }
                });
            }
        });
    });

    // 展示广告表格
    advertTable = $("#advert_table").myDataTable({
        url: "web/home/advert/list.json",
        searchBtn: $searchAdvertBtn,
        sScrollY: "450px",
        sScrollX: true,
        sScrollXInner: "100%",
        aaSorting: [[6, "desc"]],
        aLengthMenu: [10, 30, 50, 100],
        aoColumns: [{
            mData: "checkbox",
            sTitle: "<label class='pos-rel' title='全选'><input type='checkbox' class='ace'><span class='lbl'></span></label>",
            sWidth: "50px",
            sClass: "center",
            bSortable: false,
            bSearchable: false,
            sDefaultContent: "",
            fnCreatedCell: function (cell, cellData, rowData, row, col) {
                var $cell = $(cell);

                $cell.html("<label class='pos-rel'><input type='checkbox' class='ace' data-id='{0}'><span class='lbl'></span></label>".format(rowData.id));
            }
        }, {
            mData: "homeAdUrl",
            sName: "homeAdUrl",
            sTitle: "广告图片",
            sWidth: "300px",
            sDefaultContent: "",
            fnCreatedCell: function (cell, cellData, rowData, row, col) {
                var $cell = $(cell);
                var homeAdUrl = rowData.homeAdUrl;

                if ($.startsWithStr(homeAdUrl, "http://") || $.startsWithStr(homeAdUrl, "https://")) {
                    $cell.html("<img class='img-max-width-p-100' src='{0}'>".format(homeAdUrl));
                } else {
                    $cell.html("<img class='img-max-width-p-100' src='{0}{1}'>".format(globalBasePath, homeAdUrl));
                }
            }
        }, {
            mData: "homeAdName",
            sName: "homeAdName",
            sTitle: "广告标题"
        }, {
            mData: "homeAdToUrl",
            sName: "homeAdToUrl",
            sTitle: "广告跳转URL"
        }, {
            mData: "homeAdCreatePerson",
            sName: "homeAdCreatePerson",
            sTitle: "创建人",
            sWidth: "150px"
        }, {
            mData: "isShow",
            sName: "isShow",
            sTitle: "广告状态",
            sWidth: "100px",
            sDefaultContent: "",
            fnCreatedCell: function (cell, cellData, rowData, row, col) {
                var $cell = $(cell);

                // 是
                if (rowData.isShow == "1") {
                    $cell.html("<span class='label label-lg label-success'>显示</span>");

                    // 否
                } else if (rowData.isShow == "0") {
                    $cell.html("<span class='label label-lg label-danger'>隐藏</span>");
                }
            }
        }, {
            mData: "homeAdCreateTime",
            sName: "homeAdCreateTime",
            sTitle: "<i class='ace-icon iconfont icon-time bigger-110'></i>时间",
            sWidth: "100px",
            sDefaultContent: "",
            fnCreatedCell: function (cell, cellData, rowData, row, col) {
                var $cell = $(cell);

                $cell.html(rowData.homeAdCreateTime.substring(0, 10));
            }
        }, {
            mData: "operator",
            sTitle: "操作",
            sWidth: "100px",
            bSortable: false,
            bSearchable: false,
            sDefaultContent: "<div class='hidden-sm hidden-xs action-buttons'></div>",
            fnCreatedCell: function (cell, cellData, rowData, row, col) {
                // 单元格的 jQuery 对象
                var $cell = $(cell);

                if ($.hasPermission("advert:is_show")) {
                    // 显示-关
                    if (rowData.isShow == "1") {
                        $cell.find("div.action-buttons").append("<a class='is_show_close c-red' title='隐藏【{0}】' data-id='{1}' data-toggle='tooltip' data-placement='left' href='javascript:void(0);'><i class='ace-icon iconfont icon-switch-off bigger-200'></i></a>".format(rowData.homeAdName, rowData.id));

                        // 隐藏-开
                    } else if (rowData.isShow == "0") {
                        $cell.find("div.action-buttons").append("<a class='is_show_open c-green' title='显示【{0}】' data-id='{1}' data-toggle='tooltip' data-placement='left' href='javascript:void(0);'><i class='ace-icon iconfont icon-switch-on bigger-200'></i></a>".format(rowData.homeAdName, rowData.id));
                    }
                }
            }
        }],
        successFn: function () {
            $("[data-toggle='tooltip']").tooltip();
        }
    });

    /**
     *
     * 搜索数据。
     *
     */
    function searchData() {
        // 创建人
        if ($.isNotBlank($homeAdCreatePerson.val()) && ($homeAdCreatePerson.val().length > 50)) {
            $.toast({
                top: 5,
                msg: "创建人的长度不能大于50个字",
                type: "error",
                close: 3000
            });

            return;
        }

        // 广告标题
        if ($.isNotBlank($homeAdName.val()) && ($homeAdName.val().length > 500)) {
            $.toast({
                top: 5,
                msg: "广告标题的长度不能大于500个字",
                type: "error",
                close: 3000
            });

            return;
        }

        $homeAdName.val($.trim($homeAdName.val()));
        $homeAdCreatePerson.val($.trim($homeAdCreatePerson.val()));

        // 搜索开始…
        if ($.isNotNull(advertTable)) {
            advertTable.myAjaxData = {
                isShow: $isShow.val(),
                endDate: $endDate.val(),
                startDate: $startDate.val(),
                homeAdName: $homeAdName.val(),
                homeAdCreatePerson: $homeAdCreatePerson.val()
            };

            // 刷新广告表格（分页重置）
            advertTable.ajax.reload();
        }
    }
});